import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import '../models/posts.dart';
import '../models/comment.dart';
import '../services/posts_service.dart';
import '../services/token_manager.dart';

class PostDetailPage extends StatefulWidget {
  final int postId;

  const PostDetailPage({super.key, required this.postId});

  @override
  State<PostDetailPage> createState() => _PostDetailPageState();
}

class _PostDetailPageState extends State<PostDetailPage> {
  final PostsService _postsService = PostsService();
  Posts? _post;
  bool _isLoading = true;
  String? _errorMessage;
  int _currentImageIndex = 0;
  bool _isLiking = false; // 点赞中状态
  List<Comment> _comments = [];
  bool _isLoadingComments = false;
  int _commentCount = 0;
  final TextEditingController _commentController = TextEditingController();
  final FocusNode _commentFocusNode = FocusNode();
  bool _isSubmittingComment = false;

  @override
  void initState() {
    super.initState();
    // 确保初始状态是干净的
    _commentController.clear();
    _commentFocusNode.unfocus();
    _loadPost();
    _loadComments();
    // 监听输入框内容变化，更新发送按钮状态
    _commentController.addListener(() {
      if (mounted) {
        setState(() {}); // 重新构建以更新发送按钮颜色
      }
    });
  }

  @override
  void didUpdateWidget(PostDetailPage oldWidget) {
    super.didUpdateWidget(oldWidget);
    // 如果 postId 变化，重新加载
    if (oldWidget.postId != widget.postId) {
      _loadPost();
      _loadComments();
    }
  }

  @override
  void dispose() {
    _commentController.dispose();
    _commentFocusNode.dispose();
    super.dispose();
  }

  Future<void> _loadPost() async {
    if (!mounted) return;
    
    // 清空输入框和焦点
    _commentController.clear();
    _commentFocusNode.unfocus();
    
    setState(() {
      _isLoading = true;
      _errorMessage = null;
      _post = null;
      _comments = [];
      _commentCount = 0;
    });

    try {
      final post = await _postsService.getById(widget.postId);
      if (!mounted) return;
      
      setState(() {
        _isLoading = false;
        _post = post;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _isLoading = false;
        _errorMessage = '$e';
        _post = null;
      });
    }
  }

  Future<void> _loadComments() async {
    if (!mounted) return;
    
    setState(() {
      _isLoadingComments = true;
      _comments = [];
      _commentCount = 0;
    });

    try {
      final comments = await _postsService.getComments(widget.postId);
      if (!mounted) return;
      
      setState(() {
        _comments = comments;
        _commentCount = comments.length;
        _isLoadingComments = false;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _isLoadingComments = false;
      });
      print('加载评论失败: $e');
    }
  }

  Future<void> _submitComment() async {
    final content = _commentController.text.trim();
    if (content.isEmpty || _isSubmittingComment) return;

    _commentFocusNode.unfocus();
    setState(() {
      _isSubmittingComment = true;
    });

    try {
      final comment = await _postsService.addComment(widget.postId, content);
      if (!mounted) return;
      
      if (comment != null) {
        _commentController.clear();
        setState(() {
          _comments.insert(0, comment);
          _commentCount = _comments.length;
          _isSubmittingComment = false;
        });
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('评论成功'), duration: Duration(seconds: 1)),
        );
      } else {
        setState(() {
          _isSubmittingComment = false;
        });
      }
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _isSubmittingComment = false;
      });
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('评论失败: $e'), backgroundColor: Colors.red),
      );
    }
  }

  // 点赞/取消点赞
  Future<void> _toggleLike() async {
    if (_post == null || _isLiking) return;

    setState(() {
      _isLiking = true;
    });

    try {
      // 调用点赞接口（PostsService 会自动获取 userId）
      final newLikeState = await _postsService.toggleLike(widget.postId);

      if (!mounted) return;

      setState(() {
        _isLiking = false;
        // 更新本地状态
        final currentLikes = _post!.likes ?? 0;
        _post = Posts(
          id: _post!.id,
          title: _post!.title,
          content: _post!.content,
          createTime: _post!.createTime,
          userId: _post!.userId,
          userName: _post!.userName,
          imageUrl: _post!.imageUrl,
          imageUrls: _post!.imageUrls,
          avatarUrl: _post!.avatarUrl,
          likes: newLikeState ? currentLikes + 1 : currentLikes - 1,
          isLiked: newLikeState,
        );
      });

      // 轻触反馈
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(newLikeState ? '已点赞 ❤️' : '已取消点赞'),
          duration: const Duration(milliseconds: 1000),
        ),
      );
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _isLiking = false;
      });
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('操作失败: $e')),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return PopScope(
      canPop: false,
      onPopInvoked: (didPop) {
        if (!didPop) {
          // 返回更新后的帖子信息
          Navigator.pop(context, _post);
        }
      },
      child: Scaffold(
        backgroundColor: Colors.white,
        resizeToAvoidBottomInset: true, // 允许键盘调整布局
        appBar: AppBar(
          elevation: 0,
          backgroundColor: Colors.white,
          foregroundColor: Colors.black,
          leading: IconButton(
            icon: const Icon(Icons.arrow_back),
            onPressed: () => Navigator.pop(context, _post),
          ),
          title: _post != null
              ? Row(
                  children: [
                    CircleAvatar(
                      radius: 18,
                      backgroundColor: Colors.grey[300],
                      backgroundImage: (_post!.avatarUrl != null && _post!.avatarUrl!.isNotEmpty)
                          ? NetworkImage(_post!.avatarUrl!)
                          : null,
                      child: (_post!.avatarUrl == null || _post!.avatarUrl!.isEmpty)
                          ? Icon(Icons.person, size: 20, color: Colors.grey[600])
                          : null,
                    ),
                    const SizedBox(width: 8),
                    Expanded(
                      child: Text(
                        _post!.userName.isNotEmpty ? _post!.userName : '匿名',
                        style: const TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w500,
                          color: Colors.black,
                        ),
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                  ],
                )
              : null,
          actions: [
            if (_post != null)
              Padding(
                padding: const EdgeInsets.only(right: 8),
                child: IconButton(
                  icon: const Icon(Icons.share_outlined),
                  onPressed: () {
                    // TODO: 实现分享功能
                  },
                  tooltip: '分享',
                ),
              ),
          ],
        ),
        body: Column(
          children: [
            Expanded(
              child: _buildBody(),
            ),
            // 底部输入栏（固定在底部）
            if (_post != null) _buildBottomBar(),
          ],
        ),
      ),
    );
  }

  Widget _buildBody() {
    if (_isLoading) {
      return const Center(child: CircularProgressIndicator());
    }

    if (_errorMessage != null || _post == null) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.error_outline, size: 64, color: Colors.grey[400]),
            const SizedBox(height: 16),
            Text(_errorMessage ?? '加载失败', style: TextStyle(color: Colors.grey[600])),
            const SizedBox(height: 16),
            ElevatedButton(onPressed: _loadPost, child: const Text('重试')),
          ],
        ),
      );
    }

    final post = _post!;

    return SingleChildScrollView(
      physics: const AlwaysScrollableScrollPhysics(),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 图片轮播（可滑动）
          if (post.imageUrls.isNotEmpty)
            Column(
              children: [
                SizedBox(
                  height: MediaQuery.of(context).size.width,
                  child: PageView.builder(
                    itemCount: post.imageUrls.length,
                    onPageChanged: (index) {
                      setState(() {
                        _currentImageIndex = index;
                      });
                    },
                    itemBuilder: (context, index) {
                      return Image.network(
                        post.imageUrls[index],
                        fit: BoxFit.cover,
                        width: double.infinity,
                        errorBuilder: (_, __, ___) => Container(
                          color: Colors.grey[200],
                          child: const Center(
                            child: Icon(Icons.broken_image, color: Colors.grey, size: 48),
                          ),
                        ),
                      );
                    },
                  ),
                ),
                // 图片指示器
                if (post.imageUrls.length > 1)
                  Padding(
                    padding: const EdgeInsets.symmetric(vertical: 12),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: List.generate(
                        post.imageUrls.length,
                        (index) => Container(
                          margin: const EdgeInsets.symmetric(horizontal: 4),
                          width: 6,
                          height: 6,
                          decoration: BoxDecoration(
                            shape: BoxShape.circle,
                            color: _currentImageIndex == index
                                ? Colors.black
                                : Colors.grey[300],
                          ),
                        ),
                      ),
                    ),
                  ),
              ],
            ),

          // 标题
          if (post.title.isNotEmpty)
            Padding(
              padding: const EdgeInsets.fromLTRB(16, 16, 16, 12),
              child: Text(
                post.title,
                style: const TextStyle(
                  fontSize: 22,
                  fontWeight: FontWeight.bold,
                  height: 1.3,
                ),
              ),
            ),

          // 内容
          if (post.content.isNotEmpty)
            Padding(
              padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
              child: Text(
                post.content,
                style: const TextStyle(
                  fontSize: 16,
                  height: 1.6,
                  color: Colors.black87,
                ),
              ),
            ),

          // 发布日期
          if (post.createTime != null)
            Padding(
              padding: const EdgeInsets.fromLTRB(16, 0, 16, 20),
              child: Text(
                post.createTime!,
                style: TextStyle(
                  fontSize: 14,
                  color: Colors.grey[600],
                ),
              ),
            ),

          // 评论列表
          if (_isLoadingComments)
            const Padding(
              padding: EdgeInsets.all(16.0),
              child: Center(child: CircularProgressIndicator()),
            )
          else if (_comments.isNotEmpty) ...[
            const Divider(height: 1, thickness: 1),
            Padding(
              padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
              child: Text(
                '评论 (${_comments.length})',
                style: const TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
            ..._comments.map((comment) => _buildCommentItem(comment)).toList(),
          ],

          const SizedBox(height: 16), // 底部间距
        ],
      ),
    );
  }

  Widget _buildBottomBar() {
    // 只要有帖子数据就显示底部栏，简化逻辑
    if (_post == null) {
      return const SizedBox.shrink();
    }

    // 使用 postId 和当前帖子ID作为 key，确保切换帖子时底部栏正确重建
    return Container(
      key: ValueKey('bottom_bar_${widget.postId}_${_post?.id}'),
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(
          top: BorderSide(color: Colors.grey[300]!, width: 0.5),
        ),
      ),
      child: Row(
        children: [
          // 左侧：输入框
          Expanded(
            child: Container(
              height: 36,
              decoration: BoxDecoration(
                color: Colors.grey[200],
                borderRadius: BorderRadius.circular(18),
              ),
              child: TextField(
                key: ValueKey('comment_input_${widget.postId}'),
                focusNode: _commentFocusNode,
                decoration: InputDecoration(
                  hintText: '爱评论的人运气都不差',
                  hintStyle: TextStyle(color: Colors.grey[600], fontSize: 14),
                  border: InputBorder.none,
                  contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
                ),
                style: const TextStyle(fontSize: 14),
                controller: _commentController,
                enabled: !_isSubmittingComment,
                maxLines: null,
                minLines: 1,
                textInputAction: TextInputAction.send,
                onSubmitted: (_) => _submitComment(),
              ),
            ),
          ),
          const SizedBox(width: 8),
          // 发送按钮
          GestureDetector(
            onTap: _isSubmittingComment ? null : _submitComment,
            child: Container(
              width: 36,
              height: 36,
              decoration: BoxDecoration(
                color: _isSubmittingComment 
                    ? Colors.grey[300] 
                    : (_commentController.text.trim().isNotEmpty 
                        ? Colors.redAccent 
                        : Colors.grey[400]),
                shape: BoxShape.circle,
              ),
              child: _isSubmittingComment
                  ? const Center(
                      child: SizedBox(
                        width: 16,
                        height: 16,
                        child: CircularProgressIndicator(
                          strokeWidth: 2,
                          valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                        ),
                      ),
                    )
                  : const Icon(
                      Icons.send,
                      color: Colors.white,
                      size: 18,
                    ),
            ),
          ),
          const SizedBox(width: 8),
          // 右侧：交互图标和数字
          Row(
            children: [
              // 点赞
              InkWell(
                onTap: _isLiking ? null : _toggleLike,
                borderRadius: BorderRadius.circular(20),
                child: Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                  child: Row(
                    children: [
                      _isLiking
                          ? const SizedBox(
                              width: 16,
                              height: 16,
                              child: CircularProgressIndicator(strokeWidth: 2),
                            )
                          : Icon(
                              _post!.isLiked ? Icons.favorite : Icons.favorite_border,
                              color: _post!.isLiked ? Colors.redAccent : Colors.grey[700],
                              size: 20,
                            ),
                      const SizedBox(width: 4),
                      Text(
                        '${_post!.likes ?? 0}',
                        style: TextStyle(
                          fontSize: 14,
                          color: Colors.grey[700],
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              const SizedBox(width: 4),
              // 评论
              InkWell(
                onTap: () {
                  // 聚焦输入框，弹出键盘
                  _commentFocusNode.requestFocus();
                },
                borderRadius: BorderRadius.circular(20),
                child: Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                  child: Row(
                    children: [
                      Icon(Icons.comment_outlined, color: Colors.grey[700], size: 20),
                      const SizedBox(width: 4),
                      Text(
                        '$_commentCount',
                        style: TextStyle(
                          fontSize: 14,
                          color: Colors.grey[700],
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ],
        ),
      );
  }

  Widget _buildCommentItem(Comment comment) {
    return GestureDetector(
      onLongPress: () => _handleLongPressComment(comment),
      child: Container(
        padding: const EdgeInsets.fromLTRB(16, 12, 16, 12),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            CircleAvatar(
              radius: 20,
              backgroundColor: Colors.grey[300],
              backgroundImage: (comment.avatarUrl != null && comment.avatarUrl!.isNotEmpty)
                  ? NetworkImage(comment.avatarUrl!)
                  : null,
              child: (comment.avatarUrl == null || comment.avatarUrl!.isEmpty)
                  ? Icon(Icons.person, size: 20, color: Colors.grey[600])
                  : null,
            ),
            const SizedBox(width: 12),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Text(
                        comment.userName,
                        style: const TextStyle(
                          fontSize: 15,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                      if (comment.createTime != null) ...[
                        const SizedBox(width: 8),
                        Text(
                          comment.createTime!,
                          style: TextStyle(
                            fontSize: 12,
                            color: Colors.grey[500],
                          ),
                        ),
                      ],
                    ],
                  ),
                  const SizedBox(height: 4),
                  Text(
                    comment.content,
                    style: const TextStyle(
                      fontSize: 14,
                      height: 1.4,
                      color: Colors.black87,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Future<void> _handleLongPressComment(Comment comment) async {
    // 获取当前用户ID
    int? currentUserId;
    try {
      final userInfo = await TokenManager.instance.getUserInfo();
      final email = userInfo['email'];
      if (email != null && email.isNotEmpty) {
        // 通过API获取userId（使用PostsService中的baseUrl）
        final response = await http.get(
          Uri.parse('${PostsService.baseUrl}/auth/userid?email=$email'),
          headers: {'Content-Type': 'application/json'},
        );
        if (response.statusCode == 200) {
          final result = jsonDecode(response.body);
          final code = result['code'];
          final data = result['data'];
          if ((code == 1 || code == 200) && data != null) {
            currentUserId = data['id'] is int ? data['id'] : int.tryParse(data['id'].toString());
          }
        }
      }
    } catch (e) {
      print('获取用户ID失败: $e');
    }
    
    // 检查是否是当前用户的评论
    if (currentUserId == null || comment.userId != currentUserId) {
      // 不是当前用户的评论，不允许删除
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('只能删除自己的评论'),
          duration: Duration(seconds: 2),
        ),
      );
      return;
    }

    // 显示删除确认对话框
    final confirm = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('删除评论'),
        content: const Text('确定要删除这条评论吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Navigator.pop(context, true),
            style: TextButton.styleFrom(
              foregroundColor: Colors.red,
            ),
            child: const Text('删除'),
          ),
        ],
      ),
    );

    if (confirm == true && comment.id != null) {
      try {
        final success = await _postsService.deleteComment(widget.postId, comment.id!);
        if (!mounted) return;

        if (success) {
          // 删除成功，从列表中移除
          setState(() {
            _comments.removeWhere((c) => c.id == comment.id);
            _commentCount = _comments.length;
          });
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(
              content: Text('删除成功'),
              duration: Duration(seconds: 1),
            ),
          );
        } else {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(
              content: Text('删除失败，请重试'),
              backgroundColor: Colors.red,
            ),
          );
        }
      } catch (e) {
        if (!mounted) return;
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('删除失败: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }
}
